package com.baizhi.shiro.realm;


import com.baizhi.entity.Admin;
import com.baizhi.entity.Role;
import com.baizhi.service.AdminService;
import com.baizhi.service.RoleService;
import lombok.Data;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Data
public class AuthorRealm extends AuthorizingRealm {

    @Resource
    private RoleService roleService;
    @Resource
    private AdminService adminService;


    /**
     *
     *  获取授权信息
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String principal = principals.getPrimaryPrincipal().toString();
        Set<Role> roleSet = roleService.findRolesByAdminAdminName(principal);
        List<Map> permissionMap = roleService.findPermissionByAdminName(principal);
        HashSet<String> roles = new HashSet<>();
        roleSet.stream().forEach((s)->{
            roles.add(s.getRoleName());
        });
       /* HashSet<String> permissions = new HashSet<>();
        permissionMap.stream().forEach((s)->{
            permissions.add(s.get("permin").toString());
        });*/

        Set<String> permissions = permissionMap.stream().map(s -> {
            return s.get("resource_permission").toString();
        }).collect(Collectors.toSet());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo();
        String username = token.getUsername();
        Admin ad = new Admin();
        ad.setAdminName(username);
        Admin admin=adminService.findAdminByField(ad);
        if (admin != null) {
            System.out.println("int AuthorRealm============");
            return new SimpleAuthenticationInfo(admin.getAdminName(), admin.getPwd(), getName());
        }
        return null;
    }
}
